package com.zhongruan.zrccddllyhn.controller;

import com.zhongruan.zrccddllyhn.pojo.Result;
import com.zhongruan.zrccddllyhn.pojo.User;
import com.zhongruan.zrccddllyhn.service.UserService;
import com.zhongruan.zrccddllyhn.utils.JWTUtil;
import com.zhongruan.zrccddllyhn.utils.ThreadLocalUtils;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
     @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result addUser(@Pattern(regexp = "^\\S{2,4}$")String username,
                          @Pattern(regexp = "^\\S{6}$")String password,
                          @Pattern(regexp = "^\\S{11}$") String user_id){
         //查询用户
        User user = userService.findByUserName(username);
        if (user == null){
            //没有占用
            //注册
            userService.addUser(username,password,user_id);
            return Result.success();
        }else {
            //占用
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{2,4}$")String username,
                        @Pattern(regexp = "^\\S{6}$")String password){

        User loginUser = userService.findByUserName(username);

        if(loginUser == null){
            return Result.error("用户不存在");
        }
        if (password.equals(loginUser.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            claims.put("password",loginUser.getPassword());
            String token = JWTUtil.getToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
    @PatchMapping("/updatePwd")
    public Result upDatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) ||
        !StringUtils.hasLength(newPwd) ||
        !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和old_pwd比对
       Map<String,Object> map = ThreadLocalUtils.get();
           String username = (String) map.get("username");
           User loginPwd = userService.findByUserName(username);
           if (!loginPwd.getPassword().equals(oldPwd)){
               return Result.error("原密码错误");
           }

        //newPwd和rePwd是否一样
        if (!newPwd.equals(rePwd)){
            return Result.error("两次输入的密码不正确");
        }
        //调用service完成密码更新
        userService.updatePwd(newPwd);

       // 删除redis中对应的token
//        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//        operations.getOperations().delete(token);
        return Result.success();

    }

    @PatchMapping("/updateCell")
    public Result upDateCell(@RequestBody Map<String,String> cell,@RequestHeader("Authorization") String token){
        //校验参数
        String oldCell = cell.get("old_cell");
        String newCell = cell.get("new_cell");

        if(!(oldCell.length() == 11) ||
        !(newCell.length() ==11)){
            return Result.error("手机号格式错误");
        }

        if (!StringUtils.hasLength(oldCell) ||
                !StringUtils.hasLength(newCell))
        {
            return Result.error("缺少必要参数");
        }
        Map<String,Object> map = ThreadLocalUtils.get();
        String username = (String) map.get("username");
        User loginCell = userService.findByUserName(username);
        if (!loginCell.getUserId().equals(oldCell)){
            return Result.error("原密码错误");
        }

        userService.updateCell(newCell);

        return Result.success();

    }



}
